/* Copyright (C) 2007-2008  klevgert  http://code.google.com/p/db4o-netbeans/

This file is part of the db4o-netbeans module suite.

db4o-netbeans is free software; you can redistribute it and/or modify it under
the terms of version 2 of the GNU General Public License as published
by the Free Software Foundation.
 
db4o-netbeans is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. */

package com.db4o.nb.util;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.reflect.ReflectClass;
import com.db4o.reflect.jdk.JdkReflector;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarFile;
import org.openide.util.Lookup;

/**
 * Class loading utilities.
 *
 * @author klevgert
 */
public class ClassLoaderUtil {
  
  private static ClassLoader classLoader = null;

  /**
   * Loads a class either from the object container or the classpath.
   * @return loaded class
   **/
  public static Object loadClass(String name, ObjectContainer oc) {
    
    Object clazz = null;
    try {
    
      clazz = oc.ext().reflector().forName(name);
      if( clazz == null ) {
        clazz = getClassLoader().loadClass(name);
      }
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
    return clazz;
  }
  
  /**
   * Creates a new instance with given class name
   *
   * @return created object. 
   */
  public static Object newInstance(String name, ObjectContainer oc) {
    
    Object instance = null;
    try {
    
      ReflectClass rclazz = oc.ext().reflector().forName(name);
      if( rclazz != null ) {
        
        instance = rclazz.newInstance();
        
      } else {
        
        Class clazz = getClassLoader().loadClass(name);
        try {
          instance = clazz.newInstance();
        } catch (InstantiationException ex) {
          ex.printStackTrace();
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        }
      } 
      
    } catch (ClassNotFoundException ex) {
      ex.printStackTrace();
    }
    return instance;
  }
  
  /**
   * Returns the classloader that loaded this plug-in; it is the 
   * plug-in class loader.
   * 
   * @return ClassLoader
   */
  public static ClassLoader getClassLoader()
  {
     return (ClassLoaderUtil.classLoader!=null)? ClassLoaderUtil.classLoader : ClassLoader.getSystemClassLoader();
  }


  /**
   * configures db4o to use a special classloader for the domain classes
   *
   */
  public static void configureClassLoader() {

    List libraries = getKnownLibraries();

    // convert to url array
    URL[] urls = (URL[]) libraries.toArray(new URL[libraries.size()]);

    ClassLoader parentCL = (ClassLoader)Lookup.getDefault().lookup(ClassLoader.class);
    
    // create new classloader
    ClassLoaderUtil.classLoader =  new URLClassLoader(urls, ClassLoader.getSystemClassLoader());

    // configure our custom classloader
    // Db4o.configure().reflectWith(new JdkReflector(ClassLoaderUtil.classLoader));

  }

  /**
   * Returns a list of known libraries. 
   * Libraries are extracted from the workspace and preferences 
   * @return
   */
  public static List getKnownLibraries() {

    // get the project libraries as a list of urls
    List libraries = new ArrayList(); // WorkspaceFacade.getLibraries();

    // get the specified libraries in the prefs and convert them to urls
    String[] prefLibs = PreferencesUtil.getSpecifiedLibraries();
    for(int i=0; i<prefLibs.length; i++) {
      try {
        URL url = new URL("file:/"+prefLibs[i]);
        libraries.add(url);
      } catch (MalformedURLException e) {
        // skip it
      }
    }

    // return the found libraries
    return libraries;
  }

  /**
   * Returns a list of known classes. 
   * Classes are extracted from the workspace and preferences 
   * @return list of classes
   */
  public static List getKnownClasses() {

    List classes = new ArrayList();
    try {
      // get the project libraries as a list of urls
      List libraries = getKnownLibraries();

      // Iterate these libs
      Iterator it = libraries.iterator();
      while( it.hasNext() ) {
        URL url = (URL)it.next();
        JarFile lib = new JarFile(url.getFile());

        for (Enumeration n = lib.entries(); n.hasMoreElements();) {
          String name = n.nextElement().toString();
          if (name.indexOf(".class") > 0 && !(name.indexOf("$") > 0)) {
            String clsName = name.substring(0, name.lastIndexOf(".")).replace('/', '.');
            if( !PreferencesUtil.isSuppressedPackage(clsName) ){
                    classes.add(clsName);
            }
          }
        }
      }
    } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
    return classes;
  }

  
}
